package com.wr.online.test.service;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.github.yulichang.base.MPJBaseMapper;
import com.github.yulichang.base.MPJBaseService;
import com.wr.online.test.model.vo.RespBean;
import com.wr.online.test.model.vo.RespBeanEnum;
import com.wr.online.test.util.TransactionalUtils;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 判断保存的情况，保存或者更新前是否要删除对应的id
 */
public interface IMyService<T, VO, M extends MPJBaseMapper<T>> extends MPJBaseService<T> {

    Long TIME_OUT_SECOND = 5L;   //超时时间,单位秒

    /**
     * 在保持数据前，删除对应数据
     *
     * @param lock
     * @param queryWrapper
     * @param saves
     * @return
     * @throws InterruptedException
     */
//    @Transactional
//    default RespBean deleteBeforeSave(final ReentrantLock lock, Wrapper<T> queryWrapper, List<T> saves) throws InterruptedException {
//        if (lock.tryLock(TIME_OUT_SECOND, TimeUnit.SECONDS)) {
//            try {
//                //1   删除
//                removeData(queryWrapper);
//                //2   插入
//                saveList(saves);
//            } finally {
//                lock.unlock();
//            }
//        } else {
//            throw new RuntimeException("服务器响应超时！");
//        }
//        return RespBean.success();
//    }

    /**
     * 根据条件删除数据
     *
     * @param queryWrapper
     */
    default void removeData(Wrapper<T> queryWrapper) {

    }

    /**
     * 批量保存
     *
     * @param saves
     */
    default void saveList(List<T> saves) {
        saveBatch(saves);
    }

    /**
     * 通过ID查询一条数据
     *
     * @param id
     * @return
     */
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    default RespBean selectOneById(Integer id) {
        return RespBean.success(getMapper().selectById(id));
    }

    /**
     * 保存一条数据
     *
     * @param t
     * @return
     */
    default RespBean saveOne(T t) {
        return TransactionalUtils.checkTransactional(getMapper().insert(t)) ? RespBean.success() : RespBean.error(RespBeanEnum.ERROR);
    }

    /**
     * 模糊分页查询批量数据
     *
     * @param vo
     * @return
     */
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    RespBean selectListPage(VO vo);

    /**
     * 通过ID删除某些数据
     *
     * @param id
     * @return
     */
    default RespBean deleteById(Integer id) {
        return TransactionalUtils.checkTransactional(getMapper().deleteById(id)) ? RespBean.success() : RespBean.error(RespBeanEnum.ERROR);
    }

    /**
     * 通过ID更新数据
     *
     * @param newData
     * @return
     */
    default RespBean updateOneById(T newData) {
        return TransactionalUtils.checkTransactional(getMapper().updateById(newData)) ?
                RespBean.success() : RespBean.error(RespBeanEnum.ERROR);
    }


    M getMapper();
}